<template>
  <div class="web w-100">
    <el-cascader style="width: 100%;" v-model="address.ids" :options="data" :props="{label:'name', children: 'child', value:keys}" @change="handleChange" placeholder="请选择居住地" />
  </div>
  <el-input class="wap" v-model="address.text" :suffix-icon="ArrowRight" readonly :placeholder="tips" @click="toggleFun()"></el-input>
  <div class="cascader-container" :class="[pupshow ? 'on' :'', showDiv ? '' : 'noani']">
    <div class="bg" :class="[pupshow ? 'fadeIn' :'fadeOut'] " @click="toggleFun"></div>
    <div class="cascader-body" :class="[pupshow ? 'fadeUp' :'fadeDown']">
      <div class="cascader-header">
        <span @click="toggleFun">取消</span>
        <span @click="confirm">确定</span>
      </div>
      <div v-for="(column, index) in columns" :key="index" class="cascader-column">
        <div v-for="item in column" :key="item.id" class="cascader-item" :class="{ active: item.id === selectedIds[index] }" @click="handleItemClick(item, index)">
          {{ item.name }}
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, watch, computed, reactive } from 'vue';
import { ArrowRight } from '@element-plus/icons-vue'

// 定义 props
const props = defineProps({
  data: {
    type: Array as () => any[],
    required: true,
  },
  show:{
    type:Boolean,
    default:false,
  },
    
  tips:{
    type:String,
    default:'请选择地址',
  },
  keys:{
    type:String,
    default:'id',
  },
  cur:{
    type:Object,
    default:{ids:[], text:''},
  },
});
const jsonIds = reactive({
  province:'',
  city:'',
  area:''
})
const showDiv = ref(false);
setTimeout(() => {
  showDiv.value = true;
},500)
const handleChange = (e:any) => {
  address.text = e.join(' / ');
  getJsonIds(e)
}

const address = reactive({
  ids:props.cur.ids,
  text:props.cur.text
})
// 定义 emits
const emit = defineEmits(['update:modelValue', 'confirm']);
// 当前选中的 ID 数组
const selectedIds = ref<number[]>([]);
// 当前列数据
const columns = ref<any[][]>([props.data]);
// 计算当前选中的路径
const selectedPath = computed(() => {
  return selectedIds.value.map((id) => {
    const item = findItemById(id);
    return item ? item.name : '';
  });
});
// 根据 ID 查找对应的节点
function findItemById(id: number): any | undefined {
  const stack: any[] = [...props.data];
  while (stack.length) {
    const node = stack.pop()!;
    if (node.id === id) return node;
    if (node.child && node.child.length) {
      stack.push(...node.child);
    }
  }
  return undefined;
}

// 点击项处理
function handleItemClick(item: any, columnIndex: number) {
  // 更新当前列的选中 ID
  selectedIds.value = selectedIds.value.slice(0, columnIndex).concat(item.id);

  // 如果有子节点，则加载下一级列
  if (item.child && item.child.length) {
    columns.value = columns.value.slice(0, columnIndex + 1).concat([item.child]);
  } else {
    // 没有子节点时停止加载
    columns.value = columns.value.slice(0, columnIndex + 1);
  }
}

// 关闭弹窗
function close() {
  emit('update:modelValue', false);
}
const getJsonIds = (e:any) => {
  if(props.keys === 'id'){
    address.ids = e;
    e.forEach((n:any, i:number) => {
      if(i === 0){ jsonIds.province = n; }
      if(i === 1){ jsonIds.city = n; }
      if(i === 2){ jsonIds.area = n; }
    })
  }
  const setdata = {text:address.text, ids:jsonIds};
  emit('confirm', setdata);
}

// 确认选择
function confirm() {
  if(selectedIds.value.length < columns.value.length) return;
  address.text = selectedPath.value.join(' / ');
  toggleFun();
  getJsonIds(selectedIds.value);
  close();
}

const pupshow = ref(false);
const toggleFun = ()=>{
  console.log('999')
  pupshow.value = !pupshow.value;
  
}
defineExpose({
  toggleFun
})
// 监听数据变化
watch(
  () => props.data,
  (newData) => {
    columns.value = [newData];
    selectedIds.value = [];
  }
);
</script>

<style lang="scss" scoped>
  .wap{display: none;}
  .noani{
    .bg,.cascader-body{opacity: 0;}
  }
.bg{
  position: fixed; left: 0; top: 0; width: 100%; height: 100%; background-color: rgba(0,0,0,0.5); z-index: var(--zindex2); display: none;
  &.fadeIn{display: block;}
}
.fadeIn,.fadeUp{animation-delay: 0.01s;}
$headH:0.8rem;
.cascader-header {
  display: flex; align-items: center;
  justify-content: space-between; position: absolute; left: 0; width: 100%; top: 0; font-size: 0.26rem; height:$headH; padding: 0 0.2rem;
  background-color: #f5f5f5;
  font-weight: bold;
}

.cascader-body {
  display: flex; position: fixed; left: 0; bottom: 0; width: 100%;border-radius: 8px 8px 0 0; overflow: hidden; background-color: #fff;
  flex: 1; z-index: var(--zindex3);
  padding-top: $headH;
}

.cascader-column {
  font-size: 0.2rem;
  padding: 0.1rem 0;
  overflow-y: auto; max-height: 40vh;
  &:nth-child(2){width: 30%;}
  &:nth-child(3){width: 36%;}
  &:nth-child(4){width: 34%;}
  &::-webkit-scrollbar {
    width: 1px;
    height: 0.8rem;
  }
}

.cascader-column:last-child {
  border-right: none;
}

.cascader-item {
  display: flex; align-items: center; padding: 0.14rem 0.06rem; line-height: 1.4; text-align: left; justify-content: center;
  cursor: pointer;
}

.cascader-item.active {
  /* color: var(--el-color-primary); */
  font-weight: bold;
  background-color: #f7f7f7; 
}

@media only screen and (max-width: 769px){
  :deep(.el-cascader){
    display: none !important;
  }
  .wap{display: block; width: 100%;}
}

</style>